import { useState } from 'react'
import { Form, Input, Button, message, Card } from 'antd'
import axios from 'axios'
import { getAuthToken } from '@/router'

export default function Security() {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)

  const handlePassword = async (values) => {
    try {
      setLoading(true)
      await axios.put('/api/v1/user/password', values, {
        headers: { Authorization: `Bearer ${getAuthToken()}` }
      })
      message.success('密码修改成功')
      form.resetFields()
    } catch (error) {
      const errorMessage = error.response?.data?.message || 
                         error.message || 
                         '修改失败，请检查网络连接'
      message.error(errorMessage)
    } finally {
      setLoading(false)
    }
  }

  const handleEmail = async (values) => {
    try {
      await axios.put('/api/v1/user/email', values, {
        headers: { Authorization: `Bearer ${getAuthToken()}` }
      })
      message.success('邮箱绑定成功')
    } catch (error) {
      const errorMessage = error.response?.data?.message || 
                         error.message || 
                         '绑定失败，请检查邮箱格式'
      message.error(errorMessage)
    }
  }

  return (
    <div className="security-forms">
      <Card title="修改密码" className="form-card" style={{ marginBottom: 24 }}>
        <Form form={form} onFinish={handlePassword}>
          <Form.Item
            name="oldPassword"
            label="原密码"
            rules={[{ 
              required: true, 
              message: '请输入原密码' 
            }]}
          >
            <Input.Password placeholder="请输入当前使用的密码" />
          </Form.Item>
          
          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { 
                min: 8, 
                message: '密码长度至少8位' 
              },
              {
                pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+/,
                message: '需包含大小写字母和数字'
              }
            ]}
          >
            <Input.Password placeholder="至少8位，包含大小写和数字" />
          </Form.Item>
          
          <Form.Item
            name="confirmPassword"
            label="确认密码"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve()
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'))
                }
              })
            ]}
          >
            <Input.Password placeholder="再次输入新密码" />
          </Form.Item>
          
          <Button 
            type="primary" 
            htmlType="submit"
            loading={loading}
            style={{ width: 120 }}
          >
            确认修改
          </Button>
        </Form>
      </Card>

      <Card title="绑定邮箱" className="form-card">
        <Form onFinish={handleEmail}>
          <Form.Item
            name="email"
            label="邮箱地址"
            rules={[
              { required: true, message: '请输入邮箱地址' },
              { 
                type: 'email', 
                message: '无效的邮箱格式',
                validateTrigger: 'onBlur'
              }
            ]}
          >
            <Input placeholder="example@domain.com" />
          </Form.Item>
          
          <Button 
            type="primary" 
            htmlType="submit"
            style={{ width: 120 }}
          >
            绑定邮箱
          </Button>
        </Form>
      </Card>
    </div>
  )
}